package models.base;

import ext.dbutils.DBUtils;
import ext.jpa.UUIDModel;
import helper.GlobalConfig;
import models.enums.AvailableStatus;
import models.enums.UserStatus;
import play.Logger;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;

/**
 * 用户历史.
 *
 * 所有操作后,记下状态.
 */
@Entity
@Table(name = "user_histories", schema = GlobalConfig.MIGAO_DB_SCHEMA)
public class UserHistory extends UUIDModel {

    /**
     * 用户.
     */
    @ManyToOne
    @JoinColumn(name = "user_id")
    public AdminUser user;

    /**
     * 变更后的所属公司.
     */
    @ManyToOne
    @JoinColumn(name = "corp_id")
    public Corp corp;

    /**
     * 变更后的用户状态.
     */
    @Enumerated(EnumType.ORDINAL)
    @Column(name = "status")
    public AvailableStatus changedStatus;

    /**
     * 变更内容.
     */
    @Lob
    @Column(name = "changed_content")
    public String changedContent;

    /**
     * 变更备注.
     */
    @Column(name = "remark", length = 200)
    public String remark;

    /**
     * 创建时间.
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 记录用户当前状态.
     */
    public static void snapUser(AdminUser user, String changedContent, String remark) {
        if (DBUtils.isOracle()) {
            Logger.info("LOG04683: Oracle暂时不支持Lob");
            return;
        }
        UserHistory userHistory = new UserHistory();
        userHistory.user = user;
        userHistory.corp = user.corp;
        userHistory.changedStatus = user.status;
        userHistory.changedContent = changedContent;
        userHistory.remark = remark;
        userHistory.createdAt = new Date();
        userHistory.save();
    }

}
